﻿using EYangFrame.DataAccess.Global;
using EYangFramework.Common.Ninject;
using EYangFramework.Domain.Entitys.ValueObjects;
using EYangFramework.Domain.Repositorys;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Menu = EYangFramework.Domain.Entitys.ValueObjects.Menu;

namespace EYangFramework.CommonForm
{
    public partial class frm_ContainerBase : Form
    {
        IRepository<Navigation> RepositoryNavigation;
        IRepository<Domain.Entitys.ValueObjects.Menu> RepositoryMenu;
        public dynamic TempTool { get; set; }
        public frm_ContainerBase(IRepository<Navigation> repository)
        {
            TempTool = GlobalInfo.TempTool;
            this.RepositoryNavigation = repository;
            InitializeComponent();
        }

        private void frm_ContainerBase_FormClosed(object sender, FormClosedEventArgs e)
        {
            (this.Tag as Form).Show();
        }

        private void frm_ContainerBase_Load(object sender, EventArgs e)
        {
            List<Navigation> navigations = RepositoryNavigation.GetAllList();
            if (this.Tag.GetType() != typeof(frm_ContainerBase))
            {
                navigations = navigations.Where(t => t.PREVIEWNAVIGATION == null).OrderBy(t=>t.ID).ToList();
            }
            else
            {
                navigations = navigations.Where(t => t.PREVIEWNAVIGATION?.ID.ToString() == TempTool.ParentID)?.OrderBy(t => t.ID).ToList();
            }
            if (!GlobalInfo.CurrentUser.ISADMIN)
            {
                navigations = navigations.Where(t => t.USERS.Any(u => u.ID == GlobalInfo.CurrentUser.ID) || t.ROLES.Any(r => r.ID == GlobalInfo.CurrentUser.ROLE.ID)).ToList();
            }
            for (int i = 0; i < navigations.Count; i++)
            {
                var item = navigations[i];
                Button button = new Button();
                button.Text = item.NAVIGATIONNAME;
                button.Visible = true;
                button.Enabled = true;
                button.Size = new Size(75, 75);
                button.Image = item.BGIMAGE == null ? null : new Bitmap(item.BGIMAGE);
                button.ImageAlign = ContentAlignment.TopCenter;
                button.Tag = $"{item.NAVIGATIONTYPE.ToString()}/{item.ID.ToString()}/{item.URL}";
                var x = i % 10;
                var y = i / 10;
                button.Location = new Point(9 + x * 81, 117 + y * 81);
                button.Click += Button_Click;
                this.panel_Container.Controls.Add(button);
            }
            toolStatusUser.Text = string.Format($"欢迎您:{GlobalInfo.CurrentUser.USERNAME}!");
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Button button = sender as Button;
            string[] tags = button.Tag.ToString().Split('/');
            NavigationType navigationType = (NavigationType)Enum.Parse(typeof(NavigationType), tags[0]);
            Form formNext;
            switch (navigationType)
            {
                case NavigationType.Module:
                    formNext= NinjectProvider.NinjectCore.GetService<frm_ContainerBase>();
                    formNext.Tag = this;
                    (formNext as frm_ContainerBase).TempTool = new { ParentID = tags[1] };
                    formNext.Show();
                    this.Hide();
                    break;
                case NavigationType.Form:
                    Type form_BaseType = Type.GetType(tags[2]);
                    Form form_Base = NinjectProvider.NinjectCore.GetService(form_BaseType) as Form;
                    form_Base.Tag = this;
                    form_Base.Show();
                    this.Hide();
                    break;
            }
        }

        private void SetMenusAuth(frm_BasicForm currentForm, string currentType)
        {
            MenuStrip menuStrip = currentForm.GetMenuMain();
            if (menuStrip == null)
            {
                return;
            }
            List<Menu> menus = RepositoryMenu.GetAllList(t => t.FORMTYPE == currentType);
            //如果当前用户是管理员或者没有设置权限,则不对菜单作权限控制
            if (GlobalInfo.CurrentUser.ISADMIN || menus == null)
            {
                return;
            }
            else
            {
                //用户拥有的权限应该包括自身拥有的权限以及其角色拥有的权限
                menus = GlobalInfo.CurrentUser.MENUS.Union(GlobalInfo.CurrentUser.ROLE.MENUS).ToList();
                if (menus == null || menus.Count <= 0)
                {
                    return;
                }
            }
            SetElementAuth(menuStrip.Items, menus);//为子节点授权
        }
        private void SetElementAuth(ToolStripItemCollection items, List<Menu> menus)
        {
            foreach (ToolStripItem item in items)
            {
                if (menus.Where(t => t.MENUNAME == item.Text).Count() > 0)
                {
                    //只有当前节点拥有权限,才对其子节点进行权限设置
                    item.Visible = true;
                    if (item.Owner.Items.Count > 0)
                    {
                        SetElementAuth(item.Owner.Items, menus);
                    }
                }
                else
                {
                    item.Visible = false;
                }
            }
        }

        private void toolButtonExit_ButtonClick(object sender, EventArgs e)
        {
            if (MessageBox.Show("你确定需要退出程序吗?", "警告!", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                GlobalInfo.IsClosed = true;
                Application.Exit();
            }
        }

        private void toolStripSplitButton1_ButtonClick(object sender, EventArgs e)
        {
            frm_ModifyPassword frmModifyPassword = new frm_ModifyPassword();
            frmModifyPassword.ShowDialog();
        }
    }
}
